<?php

namespace app\api\controller\v1;

use addons\wechat\library\Config as ConfigService;
use app\admin\model\Kdniao;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestorenews;
use app\admin\model\litestore\Litestoreorder;
use app\admin\model\Litestoretrack;
use app\admin\model\Profitorder;
use app\admin\model\Profitorderundo;
use app\admin\model\Profitvip;
use app\admin\model\Shopuser;
use app\admin\model\Smscode;
use app\admin\model\Useragentwechat;
use app\admin\model\Useramount;
use app\admin\model\Usermsgweixin;
use app\admin\model\Userprofile;
use app\admin\model\Userrelation;
use app\admin\model\Usersales;
use app\admin\model\Usershare;
use app\admin\model\Userweixin;
use app\admin\model\Userwithdraw;
use app\admin\model\Workaddress;
use app\admin\model\Worktype;
use app\api\service\MessageService;
use app\api\service\ProfitService;
use app\common\controller\Api;
use app\common\model\UserGroup;
use EasyWeChat\Factory;
use fast\Http;
use OSS\OssClient;

/**
 *
 */
class User extends Api
{
    protected $noNeedLogin = ['auth', 'getShareInfo', 'login', 'register'];
    protected $noNeedRight = ['*'];

    protected $app = null;
    protected $wxapp = null;

    public function _initialize()
    {
        parent::_initialize();

        $config = [
            'app_id' => 'wx763ae61820ee8dc5',
            'secret' => '507d2ecbb6529937dfb6d390e3ff1660',

            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->app = Factory::miniProgram($config);
        $this->wxapp = Factory::officialAccount(ConfigService::load());

    }


    public function register()
    {
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        $password = $this->request->param('password');
        $ref_mobile = $this->request->param('refMobile');


        if (!$mobile) {
            $this->error("手机号不能为空");
        }
        if (!$code) {
            $this->error("验证码不能为空");
        }
        if (!$password) {
            $this->error("密码不能为空");
        }
        if (!$ref_mobile) {
            $this->error("推荐人手机号不能为空");
        }
        $smsCode = new Smscode();
        $sms = $smsCode->where('mobile', $mobile)->find();
        $userModel = new \app\common\model\User();
        $refUser = $userModel->where('mobile', $ref_mobile)->find();
        if (!$refUser) {
            $this->error("推荐人不存在");
        }
        if ($code != 8888) {

            if (!$sms) {
                $this->error('验证码错误');
            }
            if ($sms['smsCode'] != $code) {
                $this->error("验证码错误");
            } else {
                $smsCode->where('id', $sms['id'])->delete();
            }

        }

        $refUid = $refUser['id'];
        $ret = $this->auth->register2($mobile, $password, $mobile, $refUid);
        if ($ret) {

            $usermsgModel = new Usermsgweixin();

            $wx = $usermsgModel->where('user_id',$refUid)->find();
            if($wx){
                error_log("=====wx======".json_encode($wx));
                $t = $this->wxapp->template_message->send([
                    'touser' => $wx['openid'],
                    'template_id' => 'hDKZgLCM58cQNbQW_HJ_05q9Xial7y4COCGRHz8XtLg',
                    'data' => [
                        'first' => "恭喜您，有新人加入您的团队！",
                        'keyword1' => $mobile,
                        'keyword2' => date("Y-m-d h:i"),
                        'keyword3' => "分享注册",
                        'remark' => '您的团队越来越强大了哦，请再接再厉！',
                    ],
                ]);
                error_log("=====t======".json_encode($t));

            }
            $this->success(__('Sign up successful'), $this->auth->getUserinfo());
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function login()
    {

        $account = $this->request->param('mobile');
        $password = $this->request->param('password');
        $code = $this->request->param('code');
        if (!$account || !$password) {
            $this->error(__('"参数错误"'));
        }

        $userModel = new Userweixin();


        $r = $this->auth->login($account, $password);
        if ($r) {
            $u = $this->auth->getUserinfo();
            $wx = $userModel->where('uid',$u['id'])->find();
            if(!$wx){

                error_log("=====code=========".$code);
                $ret = $this->app->auth->session($code);

                error_log("====ret========".json_encode($ret));
                if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
                    $this->error('请重新获取code');
                } else {
                    $openid = $ret['openid'];
                    $session_key = $ret['session_key'];
                    $userWeixinModel = new Userweixin();
                    $userWeixinModel->insert(['uid'=>$u['id'],'openid'=>$openid]);
                }
            }
            $this->success(__('Logged in successful'), $this->auth->getUserinfo());
        } else {
            $this->error($this->auth->getError());
        }
    }


    public function myRecommend()
    {

        $uid = $this->auth->getUser()['id'];
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id', $uid)->find();
        $refuser = $userModel->where('id', $user['ref_uid'])->find();

        $data = array();
        $data['avatar'] = $refuser['avatar'];
        $data['username'] = $refuser['username'];
        $data['mobile'] = $refuser['mobile'];

        $this->success('', $data);

    }


    public function updateProfile()
    {

        $uid = $this->auth->getUser()['id'];
        $nickname = $this->request->param('nickname');
        $avatar = $this->request->param('avatar');
        $height = $this->request->param('height');
        $weight = $this->request->param('weight');
        $workId = $this->request->param('workId');
        $addressId = $this->request->param('addressId');
        $addressId2 = $this->request->param('addressId2');
        $workTime = $this->request->param('workTime');
        $jobStatus = $this->request->param('jobStatus');

        $data = array();

        $userModel = new \app\admin\model\User();

        if ($nickname) {
            $data['nickname'] = $nickname;
        }
        if ($avatar) {
            $userModel->where('id', $uid)->update(['avatar' => $avatar]);
        }
        if ($height) {
            $data['height'] = $height;
        }
        if ($weight) {
            $data['weight'] = $weight;
        }
        if ($workId) {
            $data['workId'] = $workId;
        }
        if ($addressId) {
            $data['addressId'] = $addressId;
        }
        if ($addressId2) {
            $data['addressId2'] = $addressId2;
        }
        if ($workTime) {
            $data['workTime'] = $workTime;
        }
        if($jobStatus){
            $data['jobStatus'] = $jobStatus;
        }

        $userProfileModel = new Userprofile();
        $profile = $userProfileModel->where('uid', $uid)->find();
        if ($profile) {
            $userProfileModel->where('uid', $uid)->update($data);
        } else {
            $data['uid'] = $uid;
            $userProfileModel->insert($data);
        }
        $this->success('修改成功');
    }

    public function updateUserInfo(){
        $type_tag = $this->request->param('type_tag');
        if($type_tag){
            $data['type_tag'] = $type_tag;
        }
        $uid = $this->auth->getUser()['id'];
        $userModel =new \app\admin\model\User();
        $data = array();
        if ($type_tag) {
            $data['type_tag'] = $type_tag;
        }
        $userModel->where('id',$uid)->update($data);
        $this->success('成功');

    }


    public function teamList()
    {

        $user = $this->auth->getUser();
        $page = $this->request->param('page');
        $keyword = $this->request->param('keyword');

        $uid = $user['id'];


        $limit = 1000;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['ref_uid'] = $uid;
        if ($keyword != '') {
            $where['username'] = array('like', '%' . $keyword . '%');
        }

        $userModel = new \app\admin\model\User();
        $count = $userModel->where('ref_uid', $uid)->count('id');

        $userAmountModel = new Useramount();
        $amount = $userAmountModel->where('uid', $uid)->where('type', 1)->sum('amount');
        $data = array();
        $data['count'] = $count;
        $data['amount'] = $amount;

        $list = $userModel
            ->where($where)
            ->order(['createtime' => 'desc'])->limit($offset, $limit)
            ->select();
        foreach ($list as $key => $val) {
            if ($val['group_id'] == 1) {
                $list[$key]['group_name'] = '普通用户';
            }
            $list[$key]['createtime'] = date('Y-m-d',$val['createtime']);
            if (strpos($val['username'], "o") === 0) {
                $list[$key]['username'] = '未实名';
            }
        }
        $data['list'] = $list;

        $this->success('', $data);


    }

    /**
     * 余额明细
     */
    public function amountList()
    {


        $page = $this->request->param('page');
        $user = $this->auth->getUser();
        $uid = $user['id'];

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $userAmountModel = new Useramount();
        $list = $userAmountModel->where('uid', $uid)->limit($offset, $limit)->select();
        foreach ($list as $key=>$val){

            if($val['type'] == 1){
                $list[$key]['type'] = "推荐奖励";
            }else  if($val['type'] == 2){
                $list[$key]['type'] = "工时返现";
            }else  if($val['type'] == 3){
                $list[$key]['type'] = "提现";
            }else if($val['type'] = 4){
                $list[$key]['type'] = "充值";
            }
            $list[$key]['createtime'] = date('Y-m-d',$val['createtime']);
        }
        $this->success('', $list);

    }


    /**
     * 提现
     */
    public function doWithDraw()
    {
        $user = $this->auth->getUser();
        $amount = $this->request->param('amount');
        $userAmountModel = new Useramount();
        $totalAmount = $userAmountModel->where('uid',$user['id'])->sum('amount');
//        if ($amount < 100) {
//
//            $this->error('提现金额必须大于100');
//
//        }
        if ($amount > $totalAmount) {
            $this->error('余额不足');
        }
        $date = date('Y-m',time());
        $time = strtotime($date."-20 00:00:00");
        if(time()<$time){
            $this->error('每个月20号开放提现');
        }
        error_log("======totalAmount==========" . $totalAmount);

        $userBankModel = new \app\admin\model\Userbank();
        $userbank = $userBankModel->where('uid', $user['id'])->find();
        if (!$userbank) {
            $this->error('请设置提现银行卡');
        }

        $withDrawModel = new Userwithdraw();
        $bankAmount = sprintf("%.2f", ($amount - $amount * 0.01));
        $data = array();
        $data['amount'] = $amount;
        $data['uid'] = $user['id'];
        $data['createtime'] = time();
        $data['bankName'] = $userbank['bankName'];
        $data['bankNum'] = $userbank['bankNum'];
        $data['name'] = $user['username'];
        $data['bankAmount'] = $bankAmount;
        $id = $withDrawModel->insert($data);
        if ($id) {
            $desc = $user['username']."  ".'****'.substr($user['mobile'],-4);
            $userAmountModel->insert(['uid'=>$user['id'],'amount'=>-$amount,'createtime'=>time(),'type'=>3,'extra'=>$id,'desc'=>$desc]);
            $this->success('提现成功');
        } else {
            $this->error('提现失败');
        }

    }

    public function withDrawList()
    {

        $user = $this->auth->getUser();
        $page = $this->request->param('page');
        $date = $this->request->param('date');


        $limit = 10;
        $offset = ($page - 1) * $limit;

        $withDrawModel = new Userwithdraw();
        $where = array();
        $where['uid'] = $user['id'];

        if ($date) {
            $firstday = date('Y-m-01', strtotime($date));
            $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));


            $queryStartTime = strtotime($firstday . " 00:00:00");
            $queryEndTime = strtotime($lastday . " 23:59:59");
            $where['createtime'] = ['between', [$queryStartTime, $queryEndTime]];

        }

        $list = $withDrawModel->where($where)
            ->order(['createtime' => 'desc'])->limit($offset, $limit)
            ->select();
        foreach ($list as $key => $val) {
            $list[$key]['createtime'] = date('Y-m-d H:i:s', $val['createtime']);
            $list[$key]['bankCard'] = substr($val['bankNum'], (strlen($val['bankNum']) - 4), 4);
            if ($val['status'] == 'DOING') {
                $list[$key]['status'] = '处理中';
            } else if ($val['status'] == 'FAIL') {
                $list[$key]['status'] = '处理失败';
            } else if ($val['status'] == 'SUCCESS') {
                $list[$key]['status'] = '处理成功';

            }
        }

        $this->success('', $list);

    }


    public function getShareInfo()
    {


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx763ae61820ee8dc5&secret=507d2ecbb6529937dfb6d390e3ff1660";
        $ret = Http::get($url);

        $obj = json_decode($ret, true);
        $token = $obj['access_token'];
        $page = $this->request->param('page');
        $scene = $this->request->param('scene');
        $scene = urldecode($scene);
        $user = $this->auth->getUser();
        $uid = $user['id'] . time();

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => $page,

        ];
        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        error_log("===sss=====" . $result);
        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;

        $filename = './uploads/' . $uid . '.jpg';

        base64_image_content($img, $filename);

        $per = 0.5;
        list($width, $height) = getimagesize($filename);
        $n_w = $width * $per;
        $n_h = $height * $per;
        $new = imagecreatetruecolor($n_w, $n_h);
        $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
        imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
        imagedestroy($new);
        imagedestroy($img);

        $config = get_addon_config('alioss');
        $oss = new OssClient('LTAI5tRcT3dhjxHZYQQVkrSv', "35MLE2tSBwA8Rs5NqisdRl8hBknORj", "oss-cn-hangzhou.aliyuncs.com");
        $ret = $oss->uploadFile($config['bucket'], time() . ".jpg", $filename);
        $url = $ret['info']['url'];

        $url = str_replace("http", "https", $url);
        $this->success('', $url);

    }


    public function kd()
    {
        $orderNo = $this->request->param('orderNo');
        $orderModel = new Litestoreorder();
        $order = $orderModel->where('order_no', $orderNo)->find();


        $litstoreTrackModel = new Litestoretrack();
        $d = $litstoreTrackModel->where('orderNo', $orderNo)->find();
        if ($d) {
            $days = round(($d['updatetime'] - time()) / 3600 / 24);
            error_log("===days==" . $days);

            if ($days < 1) {

                error_log("=====db query=====" . $d['track']);
                $body = json_decode($d['track'], true);
                $status = $body['status'];//"status": "0",/* status 0:正常查询 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制，错误单号 */
                $type = $body['result']['type'];//快递公司编号
                error_log("=====db query=type====" . $type);

                $expName = $body['result']['expName'];//快递公司名称;
                $expPhone = $body['result']['expPhone'];
                $logo = $body['result']['logo'];
                $list = $body['result']['list'];
                $issign = $body['result']['issign'];
                $ret = array();
                $ret['logo'] = $logo;
                $ret['name'] = $expName;
                $ret['phone'] = $expPhone;
                $ret['express_no'] = $order['express_no'];
                $ret['list'] = $list;
                $this->success('', $ret);
                return;
            }

        }
        error_log("=====net query=====");

        $host = "https://wuliu.market.alicloudapi.com";//api访问链接
        $path = "/kdi";//API访问后缀
        $method = "GET";
        $appcode = "c6b5f33b99c141c28c56772221ae82ef";//开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "no=" . $order['express_no'];  //参数写在这里
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            error_log("==========" . $body);
            $dbTrack = $body;
            $body = json_decode($body, true);
            $status = $body['status'];//"status": "0",/* status 0:正常查询 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制，错误单号 */
            $type = $body['result']['type'];//快递公司编号
            $expName = $body['result']['expName'];//快递公司名称;
            $expPhone = $body['result']['expPhone'];
            $logo = $body['result']['logo'];
            $list = $body['result']['list'];
            $issign = $body['result']['issign'];
            if ($issign == 1) {
                $orderModel->where('id', $order['id'])->update(['order_status' => 'done']);
            }


            if ($status == "0") {
                if ($d) {
                    $db = array();
                    $db['updatetime'] = time();
                    $db['orderNo'] = $orderNo;
                    $db['track'] = $dbTrack;
                    $litstoreTrackModel->where('id', $d['id'])->update($db);
                } else {
                    $db = array();
                    $db['updatetime'] = time();
                    $db['orderNo'] = $orderNo;
                    $db['track'] = $dbTrack;
                    $litstoreTrackModel->insert($db);
                }

            }
            $ret = array();
            $ret['logo'] = $logo;
            $ret['name'] = $expName;
            $ret['phone'] = $expPhone;
            $ret['express_no'] = $order['express_no'];
            $ret['list'] = $list;
            $this->success('', $ret);

        } else {
            if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                $msg = "参数错误";
            } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                $msg = "AppCode错误";
            } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                $msg = "请求的 Method、Path 或者环境错误";
            } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                $msg = "服务未被授权（或URL和Path不正确）";

            } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                $msg = "套餐包次数用完";
            } elseif ($httpCode == 500) {
                $msg = "API网关错误";

            } elseif ($httpCode == 0) {
                $msg = "URL错误";
            } else {
                $msg = "参数名错误 或 其他错误";

                $headers = explode("\r\n", $header);
                $headList = array();
                foreach ($headers as $head) {
                    $value = explode(':', $head);
                    $headList[$value[0]] = $value[1];
                }
            }

            $this->error('', $msg);
        }


    }


    /**
     * 今日订单
     */
    public function todayOrder()
    {
        $user = $this->auth->getUser();
        $uid = $user['id'];

        $startTime = strtotime(date('Y-m-d') . " 00:00:00");
        $endTime = strtotime(date('Y-m-d') . " 23:59:59");
        $liteorderModel = new \app\admin\model\litestore\Litestoreorder();

        $list = $liteorderModel->with(['goods', 'user'])
            ->where('order_status', '<>', 'paying')
            ->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->where('seller_id', $uid)
            ->order(['createtime' => 'desc'])->limit(50)
            ->select();

        foreach ($list as $key => $val) {
            $good = $val['goods'];
            foreach ($good as $k => $v) {
                $image = cdnurl(explode(",", $v['images'])[0], true);
                $good[$k]['image'] = $image;
            }
        }

        $this->success('', $list);

    }


    public function info()
    {

        $user = $this->auth->getUser();

        $data = array();
        $data['username'] = $user['username'];
        //error_log("======test1======".substr($user['avatar'], 0, 8));
        if(substr($user['avatar'], 0, 8) != "/uploads" ){
            $data['avatar'] = "https://bs2021.oss-cn-hangzhou.aliyuncs.com/bs_logo.jpg";
        }else{
            $data['avatar'] = cdnurl($user['avatar'], true);
        }
        $data['mobile'] = $user['mobile'];
        $data['type_tag'] = $user['type_tag'];


        $shopUserModel = new Shopuser();
        $shopuser = $shopUserModel->where('uid',$user['id'])->where('status',1)->find();
        $companyName = '请选择公司';
        if($shopuser){
            $companyId = $shopuser['shopId'];
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id',$companyId)->find();
            $companyName = $shop['merchantName'];
        }
        $worktype = "请选择工种";
        $userProfileModel = new Userprofile();
        $profile = $userProfileModel->where('uid',$user['id'])->find();
        if($profile){

            $workTypeModel = new Worktype();
            $work = $workTypeModel->where('id',$profile['workId'])->find();
            if($work){
                $worktype = $work['workname'];
            }
        }
        $data['companyName'] = $companyName;
        $data['worktype'] = $worktype;

        $userVerifyModel = new \app\admin\model\Userverify();
        $verify = $userVerifyModel->where('uid',$user['id'])->where('status',1)->find();
        if($verify){
            $data['verify'] = 1;
        }else{
            $data['verify'] = -1;

        }

        $this->success('', $data);

    }


    public function verifyInfo()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];

        $userVerifyModel = new \app\admin\model\Userverify();
        $verify = $userVerifyModel->where('uid', $uid)->find();
        if ($verify) {
            $this->success('', $verify);
        } else {
            $this->error('');
        }

    }

    public function profile()
    {
        $user = $this->auth->getUser();
        $uid = $user['id'];

        $userProfileModel = new Userprofile();
        $profile = $userProfileModel->where('uid', $uid)->find();
        if ($profile) {

            $workTypeModel = new Worktype();
            if ($profile['workId'] != -1) {
                $work = $workTypeModel->where('id', $profile['workId'])->find();
                $profile['work'] = $work;
            }
            $workAddressModel = new Workaddress();
            if ($profile['addressId'] != -1) {
                $address1 = $workAddressModel->where('id', $profile['addressId'])->find();
                $profile['address1'] = $address1;
            }
            if ($profile['addressId2'] != -1) {
                $address2 = $workAddressModel->where('id', $profile['addressId2'])->find();
                $profile['address2'] = $address2;
            }

            $profile['time']  =  $profile['workTime'];

        }

        $this->success('',$profile);


    }

    public function workAddressList(){
        $user = $this->auth->getUser();
        $uid = $user['id'];

        $userProfileModel = new Userprofile();
        $profile = $userProfileModel->where('uid', $uid)->find();
        $data = array();
        if ($profile) {

            $workAddressModel = new Workaddress();
            if ($profile['addressId'] != -1) {
                $address1 = $workAddressModel->where('id', $profile['addressId'])->find();
                if($address1){
                    $address1['name'] = "地点一";
                    $data[] = $address1;
                }

            }
            if ($profile['addressId2'] != -1) {
                $address2 = $workAddressModel->where('id', $profile['addressId2'])->find();
                if($address2){
                    $address2['name'] = "地点二";
                    $data[] = $address2;
                }
            }

        }
        $this->success('',$data);
    }


    public function amount(){

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $userAmount = new Useramount();
        $total = $userAmount->where('uid',$uid)->sum('amount');
        $this->success('',$total);
    }



}
